package com.whpost.service.service.cwqf;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beust.ah.A;
import com.whpost.service.dao.cwqf.*;
import com.whpost.service.entity.cwqf.*;
import com.whpost.service.entity.cwqf.TbCrmCustomer;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.tools.ToolBean;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class TbCrmCustomerServices extends BaseServices<TbCrmCustomerMapper, TbCrmCustomer> {

    @Resource
    private VwCwqfMapper vwCwqfMapper;
    @Resource
    private VwKhqfSummaryMapper vwKhqfSummaryMapper;
    @Resource
    private VwKhqfZySummaryMapper vwKhqfZySummaryMapper;
    @Resource
    private VwKhjlqfSummaryMapper vwKhjlqfSummaryMapper;

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String curpage = "",pagesize="",cxmc="",sfjm="";
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }

            if (StringUtils.isEmpty(sfjm)) sfjm = "1";
            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            Page<TbCrmCustomer> page = new Page<>(Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<TbCrmCustomer> tbCrmCustomerListInfo = new ListInfo<>();
            QueryWrapper<TbCrmCustomer> tbCrmCustomerQueryWrapper = new QueryWrapper<TbCrmCustomer>();
            if (!StringUtils.isEmpty(cxmc)){
                tbCrmCustomerQueryWrapper.like("party_name",cxmc);
            }

            IPage<TbCrmCustomer> tQfkbBkIPage = getBaseMapper().selectPage(page,tbCrmCustomerQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(tQfkbBkIPage.getTotal());
            pageInfo.setCurPage(tQfkbBkIPage.getCurrent());
            pageInfo.setPageSize(tQfkbBkIPage.getSize());
            pageInfo.setPageTotal(tQfkbBkIPage.getPages());

            // 对结果集进行去重：根据PARTY_CODE分组，只保留第一条记录
            List<TbCrmCustomer> distinctList = tQfkbBkIPage.getRecords().stream()
                    // 以PARTY_CODE为key分组，遇到重复时保留第一个元素
                    .collect(Collectors.toMap(
                            TbCrmCustomer::getPartyCode,  // 分组键：PARTY_CODE
                            Function.identity(),          // 分组值：对象本身
                            (existing, replacement) -> existing  // 重复时保留已有元素
                    ))
                    .values()  // 提取去重后的对象集合
                    .stream()
                    .collect(Collectors.toList());  // 转换为List

            tbCrmCustomerListInfo.setPageInfo(pageInfo);
            tbCrmCustomerListInfo.setListInfo(distinctList);  // 设置去重后的列表
            tbCrmCustomerListInfo.setUserId(loginId);

            //加密返回给前端
            if ("1".equals(sfjm)){
                ResultInfo resultInfo = new ResultInfo(200, "成功返回！",tbCrmCustomerListInfo);
                return backRtn(resultInfo,loginId);
            }else{
                //非加密,返回给其它方法使用
                return new ResultInfo(0, "成功返回！",tbCrmCustomerListInfo);
            }
        }
    }

    /**
     * 客户看板汇总
     * @param loginId
     * @return
     * @throws UnsupportedEncodingException
     */
    public ResultInfo khkb(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(401,"未登录！",null);
        }else{
            String curpage = "",pagesize="",cxmc="",zxhj="",zdhj="",wdkh="";
            Boolean applyFilter = false;
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }
            if (jsonObject.containsKey("zxhj")) {
                zxhj = jsonObject.getString("zxhj");
            }
            if (jsonObject.containsKey("zdhj")) {
                zdhj = jsonObject.getString("zdhj");
            }
            if (jsonObject.containsKey("wdkh")) {
                wdkh = jsonObject.getString("wdkh");
            }
            if (jsonObject.containsKey("applyFilter")) {
                applyFilter = jsonObject.getBoolean("applyFilter");
            }

            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "30";

            if (StringUtils.isEmpty(wdkh)) wdkh="0";


            Page<VwKhqfZySummary> page = new Page<>(Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<VwKhqfZySummary> vwKhqfZySummaryListInfo = new ListInfo<>();
            QueryWrapper<VwKhqfZySummary> khqfZySummaryQueryWrapper = new QueryWrapper<VwKhqfZySummary>();

            HsCzy hsCzy = getHsCzyMapper().selectById(loginId);

            //日期
            String rq = ToolBean.getTodayStr("yyyy-MM-dd");
            //rq="2025-09-18";
            // 将字符串转换为java.sql.Date
            Date queryDate = Date.valueOf(rq);

            //khqfSummaryQueryWrapper.eq("rq", queryDate);

            khqfZySummaryQueryWrapper.eq("is_new", "1");

            if("1".equals(wdkh)){

                khqfZySummaryQueryWrapper.inSql(
                        "kh_code",
                        "select party_code from t_cwqf_khjl_kh where czy_code = '" + hsCzy.getCode() + "'"
                );
            }

            if (!StringUtils.isEmpty(cxmc)){
                khqfZySummaryQueryWrapper.like("kh_name",cxmc);
            }

            if (applyFilter){
                if (!StringUtils.isEmpty(zxhj)){
                    khqfZySummaryQueryWrapper.ge("hj",Integer.parseInt(zxhj));
                }
                if (!StringUtils.isEmpty(zdhj)){
                    khqfZySummaryQueryWrapper.le("hj",Integer.parseInt(zdhj));
                }
            }

            khqfZySummaryQueryWrapper.likeRight("jg",hsCzy.getSsjgLsh());

            khqfZySummaryQueryWrapper.orderByDesc("hj");

            IPage<VwKhqfZySummary> khqfZySummaryPage = vwKhqfZySummaryMapper.selectPage(page,khqfZySummaryQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(khqfZySummaryPage.getTotal());
            pageInfo.setCurPage(khqfZySummaryPage.getCurrent());
            pageInfo.setPageSize(khqfZySummaryPage.getSize());
            pageInfo.setPageTotal(khqfZySummaryPage.getPages());

            vwKhqfZySummaryListInfo.setPageInfo(pageInfo);
            vwKhqfZySummaryListInfo.setListInfo(khqfZySummaryPage.getRecords());
            vwKhqfZySummaryListInfo.setUserId(loginId);//登录人员id，可以不设置也行

            //合计


            List<Map<String, BigDecimal>> hjList = vwKhqfZySummaryMapper.getHJ(rq);


            //定义返回的map
            Map<String,Object> rtnMap = new HashMap<>();



            String gljg = hsCzy.getGljg();

            List<Integer> ll = new ArrayList<>();
            // 先处理ssjgLsh，若不为空则放到列表首位
            Long ssjgLsh = hsCzy.getSsjgLsh();
            if (ssjgLsh != null) {
                Integer ssjgInt =Integer.parseInt(String.valueOf(ssjgLsh));
                if (ssjgInt != null) {
                    ll.add(ssjgInt);
                }
            }

            // 处理逻辑：拆分字符串并转换为Integer
            if (gljg != null && !gljg.trim().isEmpty()) {
                // 按逗号拆分字符串为数组
                String[] gljgArray = gljg.split(",");
                for (String str : gljgArray) {
                    try {
                        // 去除空格并转换为Integer，添加到列表
                        ll.add(Integer.parseInt(str.trim()));
                    } catch (NumberFormatException e) {
                        // 处理非数字格式的异常（如字符串中包含字母等）
                        ToolBean.info("客户看板关联机构转换错误！");
                    }
                }
            }

            List<HsJg> czyGljg2 =getHsJgMapper().czyGljg2(ll);


            rtnMap.put("rq",rq);
            rtnMap.put("khqfSummaryListInfo",vwKhqfZySummaryListInfo);
            rtnMap.put("czyGljg2",czyGljg2);
            rtnMap.put("hjList",hjList);

            ResultInfo resultInfo = new ResultInfo(200, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }

    }

    /**
     * 客户看板明细
     * @param loginId
     * @return
     * @throws UnsupportedEncodingException
     */
    public ResultInfo khkbMx(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(401,"未登录！",null);
        }else{
            String kh_code="",jg="";

            if (jsonObject.containsKey("kh_code")) {
                kh_code = jsonObject.getString("kh_code");
            }
            if (jsonObject.containsKey("jg")) {
                jg = jsonObject.getString("jg");
            }
            List<VwCwqf> vwCwqfListInfo = new ArrayList<VwCwqf>();
            QueryWrapper<VwCwqf> vwCwqfQueryWrapper = new QueryWrapper<VwCwqf>();

            HsCzy hsCzy = getHsCzyMapper().selectById(loginId);

            vwCwqfQueryWrapper.eq("kh_code",kh_code);
            vwCwqfQueryWrapper.eq("is_new", "1");

            vwCwqfQueryWrapper.eq("jg",jg);

            vwCwqfQueryWrapper.orderByDesc("hj");

            vwCwqfListInfo = vwCwqfMapper.selectList(vwCwqfQueryWrapper);

            //定义返回的map
            Map<String,Object> rtnMap = new HashMap<>();

            rtnMap.put("vwCwqfListInfo",vwCwqfListInfo);

            ResultInfo resultInfo = new ResultInfo(200, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }

    }

    /**
     * 客户经理看板汇总
     * @param loginId
     * @return
     * @throws UnsupportedEncodingException
     */
    public ResultInfo khjlkb(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(401,"未登录！",null);
        }else{
            String curpage = "",pagesize="",cxmc="";
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }

            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "30";


            Page<VwKhjlqfSummary> page = new Page<>(Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<VwKhjlqfSummary> khjlqfSummaryListInfo = new ListInfo<>();
            QueryWrapper<VwKhjlqfSummary> khjlqfSummaryQueryWrapper = new QueryWrapper<VwKhjlqfSummary>();

            //日期
            String rq = ToolBean.getTodayStr("yyyy-MM-dd");

            // 将字符串转换为java.sql.Date
            Date queryDate = Date.valueOf(rq);
            khjlqfSummaryQueryWrapper.eq("rq", queryDate);

            if (!StringUtils.isEmpty(cxmc)){
                khjlqfSummaryQueryWrapper.like("kh_name",cxmc);
            }
            khjlqfSummaryQueryWrapper.orderByAsc("hj");

            IPage<VwKhjlqfSummary> khjlqfSummaryPage = vwKhjlqfSummaryMapper.selectPage(page,khjlqfSummaryQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(khjlqfSummaryPage.getTotal());
            pageInfo.setCurPage(khjlqfSummaryPage.getCurrent());
            pageInfo.setPageSize(khjlqfSummaryPage.getSize());
            pageInfo.setPageTotal(khjlqfSummaryPage.getPages());

            khjlqfSummaryListInfo.setPageInfo(pageInfo);
            khjlqfSummaryListInfo.setListInfo(khjlqfSummaryPage.getRecords());
            khjlqfSummaryListInfo.setUserId(loginId);//登录人员id，可以不设置也行

            //合计
            List<Map<String, BigDecimal>> hjList = vwKhqfSummaryMapper.getHJ(rq);


            //定义返回的map
            Map<String,Object> rtnMap = new HashMap<>();


            rtnMap.put("rq",rq);
            rtnMap.put("khjlqfSummaryListInfo",khjlqfSummaryListInfo);
            rtnMap.put("hjList",hjList);

            ResultInfo resultInfo = new ResultInfo(200, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }

    }
}
